import Request from '../lib/Request'
import { promisify, log } from './helper.js'

const http = new Request({
	baseUrl: '',
})

http.interceptors.request.use((requestConfig) => {
	// 拦截请求的数据, 可做公共参数添加
	
	return requestConfig
})

http.interceptors.response.use(async (result) => {
	log.reportRequest(result)
	let requestData = result.data
	// 拦截返回的数据, 可做状态判断, 网络状态为200, 304等
	if(requestData.code == 0) {
		return Promise.resolve(requestData)
	}else {
		uni.showToast({
		  title: requestData.msg,
		  icon: 'none'
		})
		return Promise.reject(requestData)
	}
	
} , (err) => {
	console.log(err)
  if (err.response) {
    // 网络出现500 或 400
    if (/^50[0-9]/.test(err.response.statusCode)) {
      // 服务器错误
      uni.showToast({
        title: `服务器错误 [${err.response.statusCode}]`,
        icon: 'none'
      })
    } else if (/^4[0-1][0-9]/.test(err.response.statusCode)) {
      // 本地请求错误
      uni.showToast({
        title: `请求出错 [${err.response.statusCode}]`,
        icon: 'none'
      })
    }
    return Promise.reject(err.response)
  } else {
    // wx.request fail 错误
    uni.showToast({
      title: '请求超时 [' + err.errMsg + ']',
      icon: 'none'
    })
    return Promise.reject({...err, timeout: true})
  }
})

export default http